package com.onstar.cn.api.framework;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import com.onstar.cn.api.framework.annotation.Path;
import com.onstar.cn.api.framework.annotation.PathParams;
import com.onstar.cn.api.framework.annotation.RequestMapping;

/**
 * Get class and method annotation
 * 
 * @author 7828wc
 *
 */
public class ClazzInjectUtils {

	/**
	 * Http request url append.<br/>
	 * 
	 * @param clazz
	 * @param methodName
	 */
	public static String injectUrl(Class<?> clazz, String methodName, Object... params) {
		String url = "";
		try {
			StringBuilder urlsb = new StringBuilder();
			Class<?>[] objects = new Class<?>[params.length];
			String[] urlParams = new String[params.length];
			if (params != null && params.length > 0) {
				for (int i = 0; i < params.length; i++) {
					objects[i] = params[i].getClass();
				}
			}

			Method method = clazz.getMethod(methodName, objects);
			Path path = clazz.getAnnotation(Path.class);
			if (path != null) {
				urlsb.append(path.value());
			}

			RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
			if (requestMapping != null) {
				urlsb.append(requestMapping.value());
			}

			Annotation[][] parameterAnnotations = method.getParameterAnnotations();
			for (int k = 0; k < parameterAnnotations.length; k++) {
				for (Annotation annotation : parameterAnnotations[k]) {
					if (annotation instanceof PathParams) {
						PathParams myAnnotation = (PathParams) annotation;
						//System.out.println("value: " + myAnnotation.value());
						urlParams[k] = myAnnotation.value();
					}
				}
			}
			url = urlsb.toString();
			if (params != null && params.length > 0) {
				for (int j = 0; j < params.length; j++) {
					if (url.contains("{" + urlParams[j] + "}")) {
						if (params[j].getClass().equals(String.class)) {
							url = url.replace("{" + urlParams[j] + "}", params[j] + "");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return url;
	}
}
